#include <QtGui>
#include <QtDeclarative>
#include "box2dplugin.h"

#ifndef QT_NO_OPENGL
#include <QGLWidget>
#endif

// Lock orientation in Symbian
#ifdef Q_OS_SYMBIAN
#include <eikenv.h>
#include <eikappui.h>
#include <aknenv.h>
#include <aknappui.h>
#endif

#if defined(Q_WS_MAEMO_5) || defined(Q_OS_SYMBIAN)
    #include <QAccelerometer>
    #include "accelerometerfilter.h"

    QTM_USE_NAMESPACE
#endif


int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    Box2DPlugin plugin;
    plugin.registerTypes("Box2D");

#ifdef Q_OS_SYMBIAN
    // Lock orientation to landscape in Symbian
    CAknAppUi* appUi = dynamic_cast<CAknAppUi*> (CEikonEnv::Static()->AppUi());
    TRAP_IGNORE(
        if (appUi)
            appUi->SetOrientationL(CAknAppUi::EAppUiOrientationLandscape);
    )
#endif


#if defined Q_WS_MAEMO_5
    QRect screenGeometry(0, 0, 800, 480);
#elif defined Q_OS_SYMBIAN
    QRect screenGeometry(0, 0, 640, 360);
#else
    QRect screenGeometry(100, 100, 800, 480);
#endif

    QDeclarativeView view;

#ifndef QT_NO_OPENGL
    // Use QGLWidget to get the opengl support if available
    QGLFormat format = QGLFormat::defaultFormat();
    format.setSampleBuffers(false);

    QGLWidget *glWidget = new QGLWidget(format);
    glWidget->setAutoFillBackground(false);
    view.setViewport(glWidget);     // ownership of glWidget is taken
#endif

    QDeclarativeContext *context = view.rootContext();
    context->setContextProperty("screenWidth", screenGeometry.width());
    context->setContextProperty("screenHeight", screenGeometry.height());

    view.setSource(QUrl("qrc:/qml/Box2DDemo.qml"));

    QObject::connect((QObject*)view.engine(), SIGNAL(quit()), &app, SLOT(quit()));

#if defined(Q_WS_MAEMO_5) || defined(Q_OS_SYMBIAN)
    QAccelerometer sensor;
    AccelerometerFilter filter;

    sensor.addFilter(&filter);

    QObject::connect(&filter, SIGNAL(readingChanged(const QVariant&, const QVariant&)),
                     view.rootObject(), SLOT(gravityChanged(const QVariant&, const QVariant&)));

    sensor.start();
#endif

    view.setGeometry(screenGeometry);

#if defined(Q_WS_MAEMO_5) || defined(Q_OS_SYMBIAN) || defined(Q_WS_SIMULATOR)
    view.showFullScreen();
#else
    view.show();
#endif

    return app.exec();
}
